import { Message } from '@/proto/ProtoMsg'
import tool from '@/utils/tool'
import { HEAD_TYPE, MAGIC_CODE, VERSION_CODE, PLATFORM, VERSION_CODE_STRING } from '@/constant/protoConstant'
// 组装心跳信息
export const pingProtoData = () => {
    const uid = '' + tool.data.get('USER_INFO').userId
    let heartBeatMsg = {
        seq: 0,
        uid: uid,
        json: '心跳信息'
    }
    let message = {
        sequence: 0,
        sessionId: '',
        type: HEAD_TYPE.HEART_BEAT,
        loginRequest: undefined,
        loginResponse: undefined,
        messageRequest: undefined,
        messageResponse: undefined,
        heartBeat: heartBeatMsg,
        notification: undefined
    }
    let loginInfo = Message.encode(message).finish()
    return assembleProtoMsg(loginInfo)
}
// 组装websocket登录信息
export const webSocketLoginData = () => {
    const uid = '' + tool.data.get('USER_INFO').userId
    // 组装proto登录数据
    let loginRequestData = {
        token: tool.cookie.get('TOKEN'),
        platform: PLATFORM.WEB,
        uid: uid,
        deviceId: '',
        appVersion: VERSION_CODE_STRING
    }
    let loginData = {
        sequence: 0,
        sessionId: '',
        type: HEAD_TYPE.LOGIN_REQUEST,
        loginRequest: loginRequestData,
        loginResponse: undefined,
        messageRequest: undefined,
        messageResponse: undefined,
        heartBeat: undefined,
        notification: undefined
    }
    let loginInfo = Message.encode(loginData).finish()
    return assembleProtoMsg(loginInfo)
}
// 组装发送信息
export const messageData = (data) => {
    const uid = '' + tool.data.get('USER_INFO').userId
    let messageRequestData = {
        msgId: 0,
        from: uid,
        to: data.to,
        time: 0,
        msgType: data.msgType,
        content: data.message,
        url: data.url,
        property: '',
        fromNick: '',
        json: ''
    }
    let messageData = {
        sequence: 0,
        sessionId: '',
        type: HEAD_TYPE.MESSAGE_REQUEST,
        loginRequest: undefined,
        loginResponse: undefined,
        messageRequest: messageRequestData,
        messageResponse: undefined,
        heartBeat: undefined,
        notification: undefined
    }
    return assembleProtoMsg(Message.encode(messageData).finish())
}
// 组装二进制数据
const assembleProtoMsg = (message) => {
    let byte = message
    // 固定头部大小
    const num = 6
    // 二进制数据长度
    const len = num + byte.length
    const arrBuffer = new ArrayBuffer(len) // 初始化Byte的二进制数据缓冲区
    const dataView = new DataView(arrBuffer)
    // 魔数
    dataView.setInt16(0, MAGIC_CODE)
    // 版本信息
    dataView.setInt16(2, VERSION_CODE)
    // 数据长度
    dataView.setInt16(4, byte.length)
    for (var i = 0; i < byte.byteLength; i++) {
        dataView.setInt8(num + i, byte[i])
    }
    return dataView
}